from flask import Blueprint, request, jsonify
import os
import json
from typing import List
from utils import getResponse
import copy
import sys


# 将搜索目录改为目录
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir,os.pardir))

from app.utils import getResponse, SERVICE_DIR
# 创建蓝图
common_bp = Blueprint('common', __name__)

# 在这里添加deploy相关的接口
# @common_bp.route("/example", methods=["POST"])
# def deploy_example():
#     """部署服务示例接口"""
#     return jsonify(getResponse(200, "Common service example"))


# 获取所有微服务的名称列表
@common_bp.route("/get_all_microservices", methods=["GET"])
def get_all_microservices():
    """获取所有微服务的名称列表"""
    # 获取db/atomic_service下的所有文件夹名称作为列表
    microservices_list = os.listdir(SERVICE_DIR)
    # 过滤出文件夹名称
    microservices_list = [item for item in microservices_list if os.path.isdir(os.path.join(SERVICE_DIR, item))]
    return getResponse(200, "All microservices list", microservices_list)


# 根据服务名获取微服务的json信息
@common_bp.route("/get_microservice_info", methods=["GET"])
def get_microservice_info():
    """根据服务名获取微服务的json信息"""
    # 获取请求参数
    service_name:str = request.args.get("name",default="",type=str)
    if not service_name or service_name == "":
        return getResponse(400, "Service name is required")
    # 从db/atomic_service/{service_name}下读取json文件
    microservice_dir = os.path.join(SERVICE_DIR, service_name)
    if not os.path.exists(microservice_dir):
        return getResponse(404, f"{service_name} not found")
    # 读取json文件
    with open(os.path.join(microservice_dir, service_name+ ".json"), "r") as f:
        microservice_info = json.load(f)
    return getResponse(200, "Microservice info", microservice_info)